package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.UserLoginSourceEnum;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.DateTimeUtil;
import com.ssy.lingxi.marketing.entity.activity.*;
import com.ssy.lingxi.marketing.model.bo.ActivityDefinedBO;
import com.ssy.lingxi.marketing.model.bo.PlatformActivityTobeSignUpPageBO;
import com.ssy.lingxi.marketing.model.constant.*;
import com.ssy.lingxi.marketing.model.vo.activity.request.*;
import com.ssy.lingxi.marketing.model.vo.activity.response.*;
import com.ssy.lingxi.marketing.model.vo.common.request.CommonIdReq;
import com.ssy.lingxi.marketing.model.vo.common.response.TaskStepVO;
import com.ssy.lingxi.marketing.repository.*;
import com.ssy.lingxi.marketing.service.IPlatformActivityService;
import com.ssy.lingxi.marketing.service.IProcessFeignService;
import com.ssy.lingxi.marketing.service.IScheduleFeignService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityGoodsService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityRecordService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityRuleService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BasePlatformActivityService;
import com.ssy.lingxi.marketing.serviceimpl.component.SuitableFieldComponent;
import com.ssy.lingxi.workflow.api.model.contant.ProcessTaskStatusEnum;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 平台活动服务实现类
 * @author ds, yzc
 * @version 2.0.0
 * @date 2021/8/23
 */
@Slf4j
@Service
public class PlatformActivityServiceImpl extends BasePlatformActivityService implements IPlatformActivityService {

    @Resource
    private PlatformActivityRepository platformActivityRepository;
    @Resource
    private PlatformActivitySignUpRepository platformActivitySignUpRepository;
    @Resource
    private IProcessFeignService processFeignService;
    @Resource
    private BaseActivityRecordService activityRecordService;
    @Resource
    private ActivityMemberLevelRepository memberLevelRepository;
    @Resource
    private PlatformActivitySignUpRepository signUpRepository;
    @Resource
    private PlatformActivityInviteRepository inviteRepository;
    @Resource
    private ActivityShopRepository shopRepository;
    @Resource
    private JPAQueryFactory queryFactory;
    @Resource
    private ActivityGoodsRepository goodsRepository;
    @Resource
    private BaseActivityGoodsService activityGoodsService;
    @Resource
    private BaseActivityRuleService activityRuleService;
    @Resource
    private IScheduleFeignService scheduleFeignService;

    @Override
    public Wrapper<PageData<PlatformActivitySummaryPageResp>> pageSummary(UserLoginCacheDTO loginUser, PlatformActivityPageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, null, null);
        List<PlatformActivitySummaryPageResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivitySummaryPageResp resp = new PlatformActivitySummaryPageResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setActivitySignUpType(e.getActivitySignUpType());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            List<Integer> updateStatusList = Arrays.asList(
                    PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_SIGN_UP.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode(),
                    PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_1.getCode(),
                    PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_2.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_ONLINE.getCode(),
                    PlatformActivityInnerStatusEnum.STOP.getCode());
            resp.setUpdate(updateStatusList.contains(e.getInnerStatus()));
            List<Integer> cancelStatusList = Arrays.asList(
                    PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_SIGN_UP.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_1.getCode(),
                    PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_1.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_2.getCode(),
                    PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_2.getCode(),
                    PlatformActivityInnerStatusEnum.TO_BE_ONLINE.getCode(),
                    PlatformActivityInnerStatusEnum.STOP.getCode());
            resp.setCancel(cancelStatusList.contains(e.getInnerStatus()));
            resp.setStop(PlatformActivityInnerStatusEnum.ONGOING.getCode().equals(e.getInnerStatus()));
            resp.setRestart(PlatformActivityInnerStatusEnum.STOP.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivityAddPageResp>> pageByToBeAdd(UserLoginCacheDTO loginUser, PlatformActivityPageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, PlatformActivityOuterStatusEnum.TO_BE_SUBMIT.getCode(), PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode());
        List<PlatformActivityAddPageResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivityAddPageResp resp = new PlatformActivityAddPageResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            resp.setSubmit(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode().equals(e.getInnerStatus()));
            resp.setDelete(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode().equals(e.getInnerStatus()));
            resp.setUpdate(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivityTobeSignUpPageResp>> pageByToBeSignUp(UserLoginCacheDTO loginUser, PlatformActivityTobeSignUpReq pageVO) {
        QPlatformActivityDO activityDO = QPlatformActivityDO.platformActivityDO;
        QPlatformActivitySignUpDO signUpDO = QPlatformActivitySignUpDO.platformActivitySignUpDO;

        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(activityDO.outerStatus.eq(PlatformActivityOuterStatusEnum.TO_BE_EXAMINE_SIGN_UP.getCode()));
        predicates.and(signUpDO.status.eq(PlatformActivitySignUpInnerStatusEnum.SUBMITTED.getCode()));
        // 报名结束时间前所新建的报名数据
        predicates.and(signUpDO.createTime.loe(activityDO.signUpEndTime));
        if (StringUtils.isNotEmpty(pageVO.getStartTime())) {
            Long startTime = DateTimeUtil.toMilliSecond(DateTimeUtil.parseDateStart(pageVO.getStartTime()));
            predicates.and(activityDO.startTime.goe(startTime));
        }
        if (StringUtils.isNotEmpty(pageVO.getEndTime())) {
            Long endTime = DateTimeUtil.toMilliSecond(DateTimeUtil.parseDateEnd(pageVO.getEndTime()));
            predicates.and(activityDO.startTime.loe(endTime));
        }
        if (StringUtils.isNotEmpty(pageVO.getActivityName())) {
            predicates.and(activityDO.activityName.like("%" + pageVO.getActivityName().trim() + "%"));
        }
        if (Objects.nonNull(pageVO.getId())) {
            predicates.and(activityDO.id.eq(pageVO.getId()));
        }
        if (Objects.nonNull(pageVO.getActivityType())) {
            predicates.and(activityDO.activityType.eq(pageVO.getActivityType()));
        }

        JPAQuery<PlatformActivityTobeSignUpPageBO> queryJpaQuery = queryFactory.select(Projections.bean(PlatformActivityTobeSignUpPageBO.class,
                signUpDO.id.as("signUpId"),
                activityDO.id,
                activityDO.activityName,
                activityDO.activityType,
                activityDO.startTime,
                activityDO.endTime,
                activityDO.signUpStartTime,
                signUpDO.memberName,
                activityDO.outerStatus,
                signUpDO.status,
                signUpDO.outerExtendStatus))
                .from(signUpDO)
                .leftJoin(activityDO).on(signUpDO.platformActivity.id.eq(activityDO.id));

        queryJpaQuery.where(predicates);

        long totalCount = queryJpaQuery.fetchCount();
        List<PlatformActivityTobeSignUpPageBO> pageList = queryJpaQuery.orderBy(signUpDO.createTime.desc())
                .offset(pageVO.getCurrentOffset())
                .limit(pageVO.getPageSize())
                .fetch();

        List<PlatformActivityTobeSignUpPageResp> resultList = pageList.stream().map(o -> {
            PlatformActivityTobeSignUpPageResp resp = new PlatformActivityTobeSignUpPageResp();
            resp.setId(o.getId());
            resp.setSignUpId(o.getSignUpId());
            resp.setActivityName(o.getActivityName());
            resp.setActivityType(o.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(o.getActivityType()));
            resp.setStartTime(o.getStartTime());
            resp.setEndTime(o.getEndTime());
            resp.setSignUpStartTime(o.getSignUpStartTime());
            resp.setSignUpEndTime(o.getSignUpEndTime());
            resp.setMemberName(o.getMemberName());

            Integer outerExtendStatus = o.getOuterExtendStatus();
            // 报名审核通过和报名审核不通过
            List<Integer> SingUpExtendStatusList = Arrays.asList(PlatformActivitySignUpOuterStatusEnum.SIGN_UP_PASS.getCode(), PlatformActivitySignUpOuterStatusEnum.SIGN_UP_NO_PASS.getCode());
            if (Objects.nonNull(outerExtendStatus) && SingUpExtendStatusList.contains(outerExtendStatus)) {
                resp.setInnerStatusName("已审核报名");
                resp.setOuterStatusName(PlatformActivitySignUpOuterStatusEnum.getMessage(outerExtendStatus));
                resp.setExam(false);
            } else {
                resp.setInnerStatusName("待审核报名");
                resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(o.getOuterStatus()));
                resp.setExam(PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_SIGN_UP.getCode().equals(o.getOuterStatus()));
            }

            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(totalCount, resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivitySubmitPageResp>> pageByToBeSubmit(UserLoginCacheDTO loginUser, PlatformActivityToBeSubmitPageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode(), PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode());
        List<PlatformActivitySubmitPageResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivitySubmitPageResp resp = new PlatformActivitySubmitPageResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            resp.setSubmit(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivityExamResp>> pageByExamineStep1(UserLoginCacheDTO loginUser, PlatformActivityStep1PageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode(), PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_1.getCode());
        List<PlatformActivityExamResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivityExamResp resp = new PlatformActivityExamResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            resp.setExam(PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_1.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivityExamResp>> pageByExamineStep2(UserLoginCacheDTO loginUser, PlatformActivityStep1PageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode(), PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_2.getCode());
        List<PlatformActivityExamResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivityExamResp resp = new PlatformActivityExamResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            resp.setExam(PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_2.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<PageData<PlatformActivityOnlineResp>> pageByToBeOnline(UserLoginCacheDTO loginUser, PlatformActivityStep1PageReq pageVO) {
        Page<PlatformActivityDO> pageList = basePlatformActivityPage(loginUser, pageVO, PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode(), PlatformActivityInnerStatusEnum.TO_BE_ONLINE.getCode());
        List<PlatformActivityOnlineResp> resultList = pageList.getContent().stream().map(e -> {
            PlatformActivityOnlineResp resp = new PlatformActivityOnlineResp();
            resp.setId(e.getId());
            resp.setActivityName(e.getActivityName());
            resp.setActivityType(e.getActivityType());
            resp.setActivityTypeName(ActivityTypeEnum.getMessage(e.getActivityType()));
            resp.setStartTime(e.getStartTime());
            resp.setEndTime(e.getEndTime());
            resp.setSignUpStartTime(e.getSignUpStartTime());
            resp.setSignUpEndTime(e.getSignUpEndTime());
            resp.setOuterStatus(e.getOuterStatus());
            resp.setInnerStatus(e.getInnerStatus());
            resp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(e.getOuterStatus()));
            resp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(e.getInnerStatus()));
            resp.setOnline(PlatformActivityInnerStatusEnum.TO_BE_ONLINE.getCode().equals(e.getInnerStatus()));
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    private Wrapper<PlatformActivityDetailResp> baseDetail(UserLoginCacheDTO loginUser, CommonIdReq request,boolean querySubinfo) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        //非平台用户
        if(!UserLoginSourceEnum.BUSINESS_MANAGEMENT_PLATFORM.getCode().equals(loginUser.getLoginSource())){
            PlatformActivitySignUpDO signUpDO = signUpRepository.findByPlatformActivityIdAndMemberIdAndRoleId(platformActivityDO.getId(), loginUser.getMemberId(), loginUser.getMemberRoleId());
            if(signUpDO==null){
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
        }else  if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        PlatformActivityDetailResp detailResp = new PlatformActivityDetailResp();
        detailResp.setId(platformActivityDO.getId());
        detailResp.setActivityType(platformActivityDO.getActivityType());
        detailResp.setActivityTypeName(ActivityTypeEnum.getMessage(platformActivityDO.getActivityType()));
        detailResp.setActivitySignUpType(platformActivityDO.getActivitySignUpType());
        detailResp.setActivitySignUpTypeName(ActivitySignUpTypeEnum.getMessage(platformActivityDO.getActivitySignUpType()));
        detailResp.setActivityName(platformActivityDO.getActivityName());
        detailResp.setStartTime(platformActivityDO.getStartTime());
        detailResp.setEndTime(platformActivityDO.getEndTime());
        detailResp.setSignUpStartTime(platformActivityDO.getSignUpStartTime());
        detailResp.setSignUpEndTime(platformActivityDO.getSignUpEndTime());
        detailResp.setCreateTime(platformActivityDO.getCreateTime());
        detailResp.setEnterpriseMember(SuitableFieldComponent.parseActivitySuitableMemberType(platformActivityDO.getSuitableMemberType(), SuitableFieldComponent.pf_merchant_type_loc));
        detailResp.setPersonalMember(SuitableFieldComponent.parseActivitySuitableMemberType(platformActivityDO.getSuitableMemberType(), SuitableFieldComponent.pf_merchant_personal_type_loc));
        detailResp.setNewMember(SuitableFieldComponent.parseActivitySuitableMember(platformActivityDO.getSuitableMember(), SuitableFieldComponent.pf_new_member_loc));
        detailResp.setOldMember(SuitableFieldComponent.parseActivitySuitableMember(platformActivityDO.getSuitableMember(), SuitableFieldComponent.pf_ole_member_loc));
        detailResp.setOuterStatus(platformActivityDO.getOuterStatus());
        detailResp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(platformActivityDO.getOuterStatus()));
        detailResp.setOuterTaskStep(platformActivityDO.getOuterTaskStep());
        detailResp.setInnerStatus(platformActivityDO.getInnerStatus());
        detailResp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()));
        detailResp.setInnerTaskStep(platformActivityDO.getInnerTaskStep());
        detailResp.setActivityDefined(this.getActivityDefine(BelongTypeEnum.PLATFORM, platformActivityDO.getActivityType(), platformActivityDO.getActivityDefined()));

        if(querySubinfo) {
            // 邀请会员报名
            List<PlatformActivityInviteResp> inviteMemberRespList = Collections.emptyList();
            if (CommonBooleanEnum.NO.getCode().equals(platformActivityDO.getInviteType())) {
                inviteMemberRespList = this.listInvite(platformActivityDO.getId());
            }
            detailResp.setInviteType(platformActivityDO.getInviteType());
            detailResp.setInviteList(inviteMemberRespList);

            // 适用会员等级
            List<ActivityMemberLevelResp> memberLevelRespList = activityRuleService.listMemberLevel(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
            detailResp.setMemberLevelList(memberLevelRespList);

            // 适用商城
            List<ActivityShopResp> shopRespList = activityRuleService.listShop(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
            detailResp.setShopList(shopRespList);

            // 查询外部工作流程
            List<TaskStepVO> outerTaskList = activityRecordService.listOuterTask(platformActivityDO.getOuterProcessKey(), platformActivityDO.getOuterTaskId());
            detailResp.setOuterTaskList(outerTaskList);

            // 查询内部工作流程
            List<TaskStepVO> innerTaskList = activityRecordService.listInnerTask(platformActivityDO.getInnerProcessKey(), platformActivityDO.getInnerTaskId());
            detailResp.setInnerTaskList(innerTaskList);

            // 封装外部流转记录
            List<ActivityOuterRecordResp> platformOuterRecord = activityRecordService.getPlatformOuterRecord(loginUser, platformActivityDO.getId());
            detailResp.setOuterRecordDOList(platformOuterRecord);

            // 封装内部流转记录
            List<ActivityInnerRecordResp> platformInnerRecord = activityRecordService.getPlatformInnerRecord(loginUser, platformActivityDO.getId());
            detailResp.setInnerRecordDOList(platformInnerRecord);
        }
        return Wrapper.success(detailResp);
    }

    @Override
    public Wrapper<PlatformActivityDetailResp> detail(UserLoginCacheDTO loginUser, CommonIdReq request) {
        return baseDetail(loginUser,request,true);
    }

    @Override
    public Wrapper<PlatformActivityDetailResp> getBasedetail(UserLoginCacheDTO loginUser, CommonIdReq request) {
        return baseDetail(loginUser,request,false);
    }

    @Override
    public Wrapper<PlatformActivitySignUpDetailResp> detailSignUp(UserLoginCacheDTO loginUser, PlatformActivitySignUpDetailReq request) {
        // 报名记录
        PlatformActivitySignUpDO platformActivitySignUpDO = platformActivitySignUpRepository.findById(request.getSignUpId()).orElse(null);
        if (Objects.isNull(platformActivitySignUpDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_PLATFORM_ACTIVITY_SIGN_UP_RECORD_IS_NOT_EXISTS);
        }
        // 平台活动
        PlatformActivityDO platformActivityDO = platformActivitySignUpDO.getPlatformActivity();
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        PlatformActivitySignUpDetailResp detailResp = new PlatformActivitySignUpDetailResp();
        detailResp.setId(platformActivityDO.getId());
        detailResp.setActivityType(platformActivityDO.getActivityType());
        detailResp.setActivityTypeName(platformActivityDO.getActivityName());
        detailResp.setActivitySignUpType(platformActivityDO.getActivitySignUpType());
        detailResp.setActivitySignUpTypeName(ActivitySignUpTypeEnum.getMessage(platformActivityDO.getActivitySignUpType()));
        detailResp.setActivityName(platformActivityDO.getActivityName());
        detailResp.setStartTime(platformActivityDO.getStartTime());
        detailResp.setEndTime(platformActivityDO.getEndTime());
        detailResp.setSignUpStartTime(platformActivityDO.getSignUpStartTime());
        detailResp.setSignUpEndTime(platformActivityDO.getSignUpEndTime());
        detailResp.setCreateTime(platformActivityDO.getCreateTime());
        detailResp.setEnterpriseMember(SuitableFieldComponent.parseActivitySuitableMemberType(platformActivityDO.getSuitableMemberType(), SuitableFieldComponent.pf_merchant_type_loc));
        detailResp.setPersonalMember(SuitableFieldComponent.parseActivitySuitableMemberType(platformActivityDO.getSuitableMemberType(), SuitableFieldComponent.pf_merchant_personal_type_loc));
        detailResp.setNewMember(SuitableFieldComponent.parseActivitySuitableMember(platformActivityDO.getSuitableMember(), SuitableFieldComponent.pf_new_member_loc));
        detailResp.setOldMember(SuitableFieldComponent.parseActivitySuitableMember(platformActivityDO.getSuitableMember(), SuitableFieldComponent.pf_ole_member_loc));
        detailResp.setOuterStatus(platformActivityDO.getOuterStatus());
        detailResp.setOuterStatusName(PlatformActivityOuterStatusEnum.getMessage(platformActivityDO.getOuterStatus()));
        detailResp.setOuterTaskStep(platformActivityDO.getOuterTaskStep());
        detailResp.setInnerStatus(platformActivityDO.getInnerStatus());
        detailResp.setInnerStatusName(PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()));
        detailResp.setInnerTaskStep(platformActivityDO.getInnerTaskStep());
        detailResp.setActivityDefined(this.getActivityDefine(BelongTypeEnum.PLATFORM, platformActivityDO.getActivityType(), platformActivityDO.getActivityDefined()));
        detailResp.setMemberName(platformActivitySignUpDO.getMemberName());
        detailResp.setSignUpTime(platformActivitySignUpDO.getCreateTime());

        // 适用会员等级
        List<ActivityMemberLevelResp> memberLevelRespList = activityRuleService.listMemberLevel(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
        detailResp.setMemberLevelList(memberLevelRespList);

        // 适用商城
        List<ActivityShopResp> shopRespList = activityRuleService.listShop(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
        detailResp.setShopList(shopRespList);

        // 查询外部工作流程
        List<TaskStepVO> outerTaskList = activityRecordService.listOuterTask(platformActivityDO.getOuterProcessKey(), platformActivityDO.getOuterTaskId());
        detailResp.setOuterTaskList(outerTaskList);

        // 查询内部工作流程
        List<TaskStepVO> innerTaskList = activityRecordService.listInnerTask(platformActivityDO.getInnerProcessKey(), platformActivityDO.getInnerTaskId());
        detailResp.setInnerTaskList(innerTaskList);

        // 封装外部流转记录
        List<ActivityOuterRecordResp> platformOuterRecord = activityRecordService.getPlatformOuterRecord(loginUser, platformActivityDO.getId());
        detailResp.setOuterRecordDOList(platformOuterRecord);

        // 封装内部流转记录
        List<ActivityInnerRecordResp> platformInnerRecord = activityRecordService.getPlatformInnerRecord(loginUser, platformActivityDO.getId());
        detailResp.setInnerRecordDOList(platformInnerRecord);

        return Wrapper.success(detailResp);
    }

    @Override
    public Wrapper<PageData<PfActivitySignUpGoodsPageResp>> pageByActivityGoods(UserLoginCacheDTO loginUser, PfActivityGoodsPageReq pageVO) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(pageVO.getActivityId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        return activityGoodsService.basePagePlatformActivityGoods(null,pageVO.getActivityId(), pageVO.getCurrent(), pageVO.getPageSize(),platformActivityDO.getActivityType());
    }

    @Override
    public Wrapper<PageData<PfActivitySignUpGoodsPageResp>> pageByActivityGoodsSignUp(UserLoginCacheDTO loginUser, PfActivitySignUpGoodsPageReq pageVO) {
        // 平台进行查询, 不用传入memberId, roleId
        return activityGoodsService.basePageSignUpActivityGoods(null, null, pageVO.getSignUpId(), pageVO.getCurrent(), pageVO.getPageSize());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> savePlatformActivity(UserLoginCacheDTO loginUser, PlatformActivityAddReq request) {
        // 推断活动参与类型, 抽奖为平台参与, 非抽奖为商家参与
        Integer activitySignUpType = ActivityTypeEnum.LOTTERY.getCode().equals(request.getActivityType()) ? ActivitySignUpTypeEnum.PLATFORM.getCode() : ActivitySignUpTypeEnum.SUPPLIER.getCode();

        // 平台活动参数校验
        Wrapper<Void> platformParamWrapper = checkPlatformParam(activitySignUpType, request);
        if (ResponseCode.SUCCESS.getCode() != platformParamWrapper.getCode()) {
            return platformParamWrapper;
        }

        // 校验各种活动类型对应的参数
        Wrapper<Void> checkActivityDefineWrapper = checkActivityDefine(request.getActivityType(), request.getActivityDefined());
        if (ResponseCode.SUCCESS.getCode() != checkActivityDefineWrapper.getCode()) {
            return checkActivityDefineWrapper;
        }

        // 校验适用商城
        activityRuleService.checkShop(request.getShopList());

        // 校验适用会员等级
        if (!CollectionUtils.isEmpty(request.getMemberLevelList())) {
            activityRuleService.checkMemberLevel(request.getMemberLevelList());
        }

        // 根据jsonObject, 转成对应活动定义BO对象
        ActivityDefinedBO activityDefinedBO = this.parseActivityDefinedBO(request.getActivityType(), request.getActivityDefined());

        // 保存平台活动
        PlatformActivityDO platformActivityDO = new PlatformActivityDO();
        platformActivityDO.setActivityName(request.getActivityName());
        platformActivityDO.setStartTime(request.getStartTime());
        platformActivityDO.setEndTime(request.getEndTime());
        platformActivityDO.setActivityType(request.getActivityType());
        platformActivityDO.setMinType(this.getMinType(request.getActivityType(), request.getActivityDefined()));
        platformActivityDO.setAllowCoupon(this.getAllowCoupon(request.getActivityType(), request.getActivityDefined()));
        platformActivityDO.setActivityDefined(activityDefinedBO);
        platformActivityDO.setActivitySignUpType(activitySignUpType);
        platformActivityDO.setSuitableMember(SuitableFieldComponent.generateActivitySuitableMember(request.getNewMember(), request.getOldMember()));
        platformActivityDO.setSuitableMemberType(SuitableFieldComponent.generateActivitySuitableMemberType(request.getEnterpriseMember(), request.getPersonalMember()));
        // 商家报名活动, 报名时间
        if (ActivitySignUpTypeEnum.SUPPLIER.getCode().equals(activitySignUpType)) {
            platformActivityDO.setSignUpStartTime(request.getSignUpStartTime());
            platformActivityDO.setSignUpEndTime(request.getSignUpEndTime());
        }
        platformActivityDO.setInviteType(request.getInviteType());
        platformActivityDO.setCreateTime(System.currentTimeMillis());
        platformActivityDO.setMemberId(loginUser.getMemberId());
        platformActivityDO.setRoleId(loginUser.getMemberRoleId());
        platformActivityRepository.saveAndFlush(platformActivityDO);

        // 适用会员等级
        activityRuleService.saveMemberLevel(BelongTypeEnum.PLATFORM, platformActivityDO.getId(), request.getMemberLevelList());

        // 适用商城
        activityRuleService.saveShop(BelongTypeEnum.PLATFORM, platformActivityDO.getId(), request.getShopList());

        // 商家报名活动且指定邀请会员, 保存邀请报名参加会员
        if (ActivitySignUpTypeEnum.SUPPLIER.getCode().equals(activitySignUpType)
                && CommonBooleanEnum.NO.getCode().equals(request.getInviteType())) {
            this.saveInvite(platformActivityDO, request.getInviteList());
        }

        // 启动外部流程
        SimpleTaskCompleteVO outerTask = processFeignService.startSimpleProcess(loginUser.getMemberId(), loginUser.getMemberRoleId(), MarketingConstants.platform_activity_outer_key, platformActivityDO.getId());
        platformActivityDO.setOuterProcessKey(MarketingConstants.platform_activity_outer_key);
        platformActivityDO.setOuterStatus(outerTask.getStatus());
        platformActivityDO.setOuterTaskId(outerTask.getTaskId());
        platformActivityDO.setOuterTaskStep(outerTask.getStep());

        // 内部状态
        platformActivityDO.setInnerProcessKey(MarketingConstants.platform_activity_inner_key);
        platformActivityDO.setInnerStatus(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode());

        // 保存
        platformActivityRepository.saveAndFlush(platformActivityDO);

        // 活动结束定时任务
        scheduleFeignService.createPfActivityEndTask(loginUser, platformActivityDO);

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> updatePlatformActivity(UserLoginCacheDTO loginUser, PlatformActivityUpdateReq request) {
        // 校验适用商城
        activityRuleService.checkShop(request.getShopList());

        // 校验适用会员等级
        if (!CollectionUtils.isEmpty(request.getMemberLevelList())) {
            activityRuleService.checkMemberLevel(request.getMemberLevelList());
        }

        // 查询平台活动信息
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_RECORDS_DONT_EXIST);
        }

        // 平台活动参数校验
        Wrapper<Void> platformParamWrapper = checkPlatformParam(platformActivityDO.getActivitySignUpType(), request);
        if (ResponseCode.SUCCESS.getCode() != platformParamWrapper.getCode()) {
            return platformParamWrapper;
        }

        // 内部状态判断,只能修改待提交,审核不通过(一级),审核不通过(二级)
        List<Integer> statusList = Arrays.asList(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode(),
                PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_1.getCode(),
                PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_2.getCode());
        if (!statusList.contains(platformActivityDO.getInnerStatus())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }

        // 校验各种活动类型对应的参数
        Wrapper<Void> checkActivityDefineWrapper = checkActivityDefine(platformActivityDO.getActivityType(), request.getActivityDefined());
        if (ResponseCode.SUCCESS.getCode() != checkActivityDefineWrapper.getCode()) {
            return checkActivityDefineWrapper;
        }

        // 根据jsonObject, 转成对应活动定义BO对象
        ActivityDefinedBO activityDefinedBO = this.parseActivityDefinedBO(platformActivityDO.getActivityType(), request.getActivityDefined());

        // 拒绝状态修改后为待提交
        List<Integer> rejectStatusList = Arrays.asList(PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_1.getCode(),
                PlatformActivityInnerStatusEnum.EXAMINE_NO_PASS_2.getCode());
        if (rejectStatusList.contains(platformActivityDO.getInnerStatus())) {
            platformActivityDO.setInnerStatus(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode());
        }

        // 更新平台活动
        platformActivityDO.setActivityName(request.getActivityName());
        platformActivityDO.setStartTime(request.getStartTime());
        platformActivityDO.setEndTime(request.getEndTime());
        platformActivityDO.setSuitableMember(SuitableFieldComponent.generateActivitySuitableMember(request.getNewMember(), request.getOldMember()));
        platformActivityDO.setSuitableMemberType(SuitableFieldComponent.generateActivitySuitableMemberType(request.getEnterpriseMember(), request.getPersonalMember()));
        // 商家报名活动, 报名时间
        if (ActivitySignUpTypeEnum.SUPPLIER.getCode().equals(platformActivityDO.getActivitySignUpType())) {
            platformActivityDO.setSignUpStartTime(request.getSignUpStartTime());
            platformActivityDO.setSignUpEndTime(request.getSignUpEndTime());
        }
        platformActivityDO.setInviteType(request.getInviteType());
        platformActivityDO.setActivityDefined(activityDefinedBO);
        platformActivityDO.setMinType(this.getMinType(platformActivityDO.getActivityType(), request.getActivityDefined()));
        platformActivityDO.setAllowCoupon(this.getAllowCoupon(platformActivityDO.getActivityType(), request.getActivityDefined()));
        platformActivityRepository.saveAndFlush(platformActivityDO);

        // 适用会员等级
        activityRuleService.deleteMemberLevel(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
        activityRuleService.saveMemberLevel(BelongTypeEnum.PLATFORM, platformActivityDO.getId(), request.getMemberLevelList());

        // 适用商城
        activityRuleService.deleteShop(BelongTypeEnum.PLATFORM, platformActivityDO.getId());
        activityRuleService.saveShop(BelongTypeEnum.PLATFORM, platformActivityDO.getId(), request.getShopList());

        // 商家报名活动, 因为不能修改活动类型, 所以活动参与类型在新增的时候已经定下来并不会改变
        if (ActivitySignUpTypeEnum.SUPPLIER.getCode().equals(platformActivityDO.getActivitySignUpType())) {
            deleteInvite(platformActivityDO.getId());
            // 指定邀请会员, 保存邀请报名参加会员
            if (CommonBooleanEnum.NO.getCode().equals(request.getInviteType())) {
                this.saveInvite(platformActivityDO, request.getInviteList());
            }
        }

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> batchDelete(UserLoginCacheDTO loginUser, List<Long> idList) {
        List<PlatformActivityDO> activityDOS = platformActivityRepository.findAllById(idList);
        if (CollectionUtils.isEmpty(activityDOS)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        for (PlatformActivityDO activityDO : activityDOS) {
            if (!isBelongCurrentMember(loginUser, activityDO.getMemberId(), activityDO.getRoleId())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
            if (!PlatformActivityOuterStatusEnum.TO_BE_SUBMIT.getCode().equals(activityDO.getOuterStatus())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }
            if (!Objects.equals(activityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }
        }

        // 删除活动
        platformActivityRepository.deleteAll(activityDOS);
        // 删除会员等级
        memberLevelRepository.deleteByBelongTypeAndActivityIdIn(BelongTypeEnum.PLATFORM.getCode(), idList);
        // 删除商城
        shopRepository.deleteByBelongTypeAndActivityIdIn(BelongTypeEnum.PLATFORM.getCode(), idList);
        // 删除活动邀请会员
        inviteRepository.deleteByPlatformActivityIdIn(idList);

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> cancel(UserLoginCacheDTO loginUser, ActivityActionReq request) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        // 判断当前状态是否可取消
        if (!PlatformActivityOuterStatusEnum.canCancel(platformActivityDO.getOuterStatus())
                || !PlatformActivityInnerStatusEnum.canCancel(platformActivityDO.getInnerStatus())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_ALLOW_UPDATE);
        }

        // 更新状态
        Integer outStatus = PlatformActivityOuterStatusEnum.CANCEL.getCode();
        Integer innerStatus = PlatformActivityInnerStatusEnum.CANCEL.getCode();
        platformActivityDO.setOuterStatus(outStatus);
        platformActivityDO.setOuterTaskStep(0);
        platformActivityDO.setInnerStatus(innerStatus);
        platformActivityDO.setInnerTaskStep(0);
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 外部流转记录
        activityRecordService.savePlatformActivityOuterRecord(loginUser, platformActivityDO.getId(), outStatus, PlatformActivityOuterStatusEnum.getMessage(outStatus), ActivityStrOperateEnum.pt_outer_cancel.getMessage(), request.getReason());
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), innerStatus, PlatformActivityInnerStatusEnum.getMessage(innerStatus), ActivityStrOperateEnum.pt_inner_cancel.getMessage(), request.getReason());
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> stop(UserLoginCacheDTO loginUser, ActivityActionReq request) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.ONGOING.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_ALLOW_UPDATE);
        }

        // 更新状态
        Integer outStatus = PlatformActivityOuterStatusEnum.STOP.getCode();
        Integer innerStatus = PlatformActivityInnerStatusEnum.STOP.getCode();
        platformActivityDO.setOuterStatus(outStatus);
        platformActivityDO.setOuterTaskStep(0);
        platformActivityDO.setInnerStatus(innerStatus);
        platformActivityDO.setInnerTaskStep(0);
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 外部流转记录
        activityRecordService.savePlatformActivityOuterRecord(loginUser, platformActivityDO.getId(), outStatus, PlatformActivityOuterStatusEnum.getMessage(outStatus), ActivityStrOperateEnum.pt_outer_stop.getMessage(), request.getReason());
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), innerStatus, PlatformActivityInnerStatusEnum.getMessage(innerStatus), ActivityStrOperateEnum.pt_inner_stop.getMessage(), request.getReason());
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> restart(UserLoginCacheDTO loginUser, ActivityActionReq request) {
        long currentTimeMillis = System.currentTimeMillis();
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.STOP.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_ALLOW_UPDATE);
        }
        // 过期不允许重新启动
        if (currentTimeMillis >= platformActivityDO.getEndTime()) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_INVALID_NOT_ALLOW_UPDATE);
        }
        // 更新状态
        Integer outStatus = PlatformActivityOuterStatusEnum.ONGOING.getCode();
        Integer innerStatus = PlatformActivityInnerStatusEnum.ONGOING.getCode();
        platformActivityDO.setOuterStatus(outStatus);
        platformActivityDO.setOuterTaskStep(0);
        platformActivityDO.setInnerStatus(innerStatus);
        platformActivityDO.setInnerTaskStep(0);
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 外部流转记录
        activityRecordService.savePlatformActivityOuterRecord(loginUser, platformActivityDO.getId(), outStatus, PlatformActivityOuterStatusEnum.getMessage(outStatus), ActivityStrOperateEnum.pt_outer_restart.getMessage(), request.getReason());
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), innerStatus, PlatformActivityInnerStatusEnum.getMessage(innerStatus), ActivityStrOperateEnum.pt_inner_restart.getMessage(), request.getReason());
        return Wrapper.success();
    }

    /**
     * 判断时间戳差是否大于1秒
     * @param num1
     * @param num2
     * @return
     */
    public static boolean isDiffer(Long num1,Long num2){
        long diff = (num1-num1 % 1000) - (num2-num2 % 1000);
        return diff>999||diff<-999;
    }

    /**
     * 判断开始或结束时间是否有调整
     * @param startTime
     * @param endTime
     * @param reqStartTime
     * @param reqEndTime
     * @return
     */
    private boolean isUpdateTime(Long startTime,Long endTime,Long reqStartTime,Long reqEndTime){
        return isDiffer(startTime,reqStartTime)||isDiffer(endTime,reqEndTime);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> updateTime(UserLoginCacheDTO loginUser, PlatformActivityUpdateTimeReq request) {
        long currentTimeMillis = System.currentTimeMillis();
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        Set<Integer> recordUpdateType=new HashSet<>();
        //修改活动时间
        if(isUpdateTime(platformActivityDO.getStartTime(),platformActivityDO.getEndTime(),request.getStartTime(),request.getEndTime())) {
            // 只有该内部状态才能修改活动时间: 待审核报名、待提交审核、审核不通过(一级)、审核不通过(二级)、已终止
            if (!PlatformActivityInnerStatusEnum.canUpdateActivityTime(platformActivityDO.getInnerStatus())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }

            // 判断活动时间
            Wrapper<Void> checkTimeWrapper = this.checkPlatformActivityTime(currentTimeMillis, request.getStartTime(), request.getEndTime());
            if (ResponseCode.SUCCESS.getCode() != checkTimeWrapper.getCode()) {
                return checkTimeWrapper;
            }

            platformActivityDO.setStartTime(request.getStartTime());
            platformActivityDO.setEndTime(request.getEndTime());
            recordUpdateType.add(1);
        }

        //修改报名时间 商家报名活动
        if (ActivitySignUpTypeEnum.SUPPLIER.getCode().equals(platformActivityDO.getActivitySignUpType())
        &&isUpdateTime(platformActivityDO.getSignUpStartTime(),platformActivityDO.getSignUpEndTime(),request.getSignUpStartTime(),request.getSignUpEndTime())) {
            // 只有该内部状态才能修改报名时间: 待审核报名
            if (!PlatformActivityInnerStatusEnum.canUpdateSignUpTime(platformActivityDO.getInnerStatus())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }

            // 判断活动报名时间
            Wrapper<Void> checkSignUptTimeWrapper = this.checkPlatformActivitySignUpTime(request.getStartTime(), request.getSignUpStartTime(), request.getSignUpEndTime());
            if (ResponseCode.SUCCESS.getCode() != checkSignUptTimeWrapper.getCode()) {
                return checkSignUptTimeWrapper;
            }

            platformActivityDO.setSignUpStartTime(request.getSignUpStartTime());
            platformActivityDO.setSignUpEndTime(request.getSignUpEndTime());
            recordUpdateType.add(2);
        }

        if(recordUpdateType.size()>0) {
            // 更新活动时间
            platformActivityRepository.saveAndFlush(platformActivityDO);
            if(recordUpdateType.contains(1)) {
                // 活动结束定时任务
                scheduleFeignService.createPfActivityEndTask(loginUser, platformActivityDO);
            }
            if(recordUpdateType.contains(2)) {
                // 定时任务, [报名时间结束]触发状态变更为: 待审核报名 -> 待上线活动
                scheduleFeignService.createSignUpEndTask(loginUser, platformActivityDO);
            }
        }
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> submit(UserLoginCacheDTO loginUser, ActivitySubmitReq req) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(req.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!PlatformActivityOuterStatusEnum.TO_BE_SUBMIT.getCode().equals(platformActivityDO.getOuterStatus())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        if (!Objects.equals(platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }

        this.baseSubmit(loginUser, Collections.singletonList(platformActivityDO));

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> batchSubmit(UserLoginCacheDTO loginUser, CommonIdsReq req) {
        List<PlatformActivityDO> platformActivityDOList = platformActivityRepository.findAllById(req.getIds());
        for (PlatformActivityDO platformActivityDO : platformActivityDOList) {
            if (Objects.isNull(platformActivityDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
            if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
            if (!PlatformActivityOuterStatusEnum.TO_BE_SUBMIT.getCode().equals(platformActivityDO.getOuterStatus())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }
            if (!Objects.equals(platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.TO_BE_SUBMIT.getCode())) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
            }
        }

        this.baseSubmit(loginUser, platformActivityDOList);

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> examineSignUpUpdate(UserLoginCacheDTO loginUser, PlatformActivityExamineSignUpReq request) {
        PlatformActivitySignUpDO signUpDO = signUpRepository.findById(request.getSignUpId()).orElse(null);
        if (Objects.isNull(signUpDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_PLATFORM_ACTIVITY_SIGN_UP_NOT_EXISTS);
        }

        // 获取平台活动
        PlatformActivityDO platformActivityDO = signUpDO.getPlatformActivity();
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        if (!PlatformActivitySignUpInnerStatusEnum.SUBMITTED.getCode().equals(signUpDO.getStatus())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }

        signUpDO.setUpdateTime(System.currentTimeMillis());
        Integer outerExtendStatus = CommonBooleanEnum.YES.getCode().equals(request.getIsPass()) ? PlatformActivitySignUpOuterStatusEnum.SIGN_UP_PASS.getCode() : PlatformActivitySignUpOuterStatusEnum.SIGN_UP_NO_PASS.getCode();
        signUpDO.setOuterExtendStatus(outerExtendStatus);
        signUpRepository.saveAndFlush(signUpDO);

        // 外部流转记录
        activityRecordService.savePlatformActivitySignUpOuterRecord(loginUser, platformActivityDO.getId(), signUpDO.getId(), outerExtendStatus, PlatformActivitySignUpOuterStatusEnum.getMessage(outerExtendStatus), ActivityStrOperateEnum.pt_outer_audit_signup.getMessage(), request.getOpinion());

        // 审核报名商品状态
        List<ActivityGoodsDO> signUpActivityGoodsList = goodsRepository.findBySignUpId(signUpDO.getId());
        for (ActivityGoodsDO activityGoodsDO : signUpActivityGoodsList) {
            if (CommonBooleanEnum.YES.getCode().equals(request.getIsPass())) {
                activityGoodsDO.setAuditStatus(ActivityGoodsAuditStatusEnum.AGREE.getCode());
            } else {
                activityGoodsDO.setAuditStatus(ActivityGoodsAuditStatusEnum.REJECT.getCode());
            }
        }
        goodsRepository.saveAll(signUpActivityGoodsList);

        // 报名时间结束, 需要平台处理完所有商家提交的报名资料, 才能进入下个流程
        this.updateByAllSignUp(loginUser, platformActivityDO);

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> submitExamine(UserLoginCacheDTO loginUser, ActivitySubmitReq request) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        if (!platformActivityDO.getInnerStatus().equals(PlatformActivityInnerStatusEnum.TO_BE_SUBMIT_EXAMINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        // 执行内部流转
        platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityInner(platformActivityDO, ProcessTaskStatusEnum.GOTO_NEXT_STEP.getCode());
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()), ActivityStrOperateEnum.pt_inner_submit.getMessage(), "");
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> examineStep1Update(UserLoginCacheDTO loginUser, ActivityExamineReq request) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        if (!platformActivityDO.getInnerStatus().equals(PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_1.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        // 执行内部流转
        platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityInner(platformActivityDO, request.getIsPass());
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()), ActivityStrOperateEnum.pt_inner_examine_step1.getMessage(), request.getOpinion());
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> examineStep2Update(UserLoginCacheDTO loginUser, ActivityExamineReq request) {
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }
        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        if (!platformActivityDO.getInnerStatus().equals(PlatformActivityInnerStatusEnum.TO_BE_EXAMINE_2.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }
        // 执行内部流转
        platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityInner(platformActivityDO, request.getIsPass());
        platformActivityRepository.saveAndFlush(platformActivityDO);
        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()), ActivityStrOperateEnum.pt_inner_examine_step2.getMessage(), request.getOpinion());
        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> onlineUpdate(UserLoginCacheDTO loginUser, ActivitySubmitReq request) {
        long currentTimeMillis = System.currentTimeMillis();
        PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getId()).orElse(null);
        if (Objects.isNull(platformActivityDO)) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        if (!isBelongCurrentMember(loginUser, platformActivityDO.getMemberId(), platformActivityDO.getRoleId())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
        }

        if (!platformActivityDO.getOuterStatus().equals(PlatformActivityOuterStatusEnum.TO_BE_ONLINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }

        if (!platformActivityDO.getInnerStatus().equals(PlatformActivityInnerStatusEnum.TO_BE_ONLINE.getCode())) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_CURRENT_STATUS_NOT_ALLOW_UPDATE);
        }

        // 过期不允许上线
        if (currentTimeMillis >= platformActivityDO.getEndTime()) {
            return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_INVALID_NOT_ALLOW_UPDATE);
        }

        // 执行外部流转
        platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityOuter(platformActivityDO, ProcessTaskStatusEnum.AGREE.getCode());

        // 执行内部流转
        platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityInner(platformActivityDO, ProcessTaskStatusEnum.AGREE.getCode());
        platformActivityRepository.saveAndFlush(platformActivityDO);

        // 外部流转记录
        activityRecordService.savePlatformActivityOuterRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getOuterStatus(), PlatformActivityOuterStatusEnum.getMessage(platformActivityDO.getOuterStatus()), ActivityStrOperateEnum.pt_outer_online.getMessage(), "");

        // 内部流转记录
        activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()), ActivityStrOperateEnum.pt_inner_online.getMessage(), "");
        return Wrapper.success();
    }

    public void updateByAllSignUp(UserLoginCacheDTO loginUser, PlatformActivityDO platformActivityDO) {
        // 报名时间已经结束
        if (System.currentTimeMillis() < platformActivityDO.getSignUpEndTime()) {
            return;
        }

        // 查询平台活动下的所有商家报名信息
        List<PlatformActivitySignUpDO> signUpList = signUpRepository.findByPlatformActivityId(platformActivityDO.getId());
        if (CollectionUtil.isEmpty(signUpList)) {
            log.error("平台活动报名, 报名时间已结束, 没有商家报名,  activityId: {}", platformActivityDO.getId());
            return;
        }

        // 处理完审核报名的状态
        List<Integer> outerExtendStatusList = Arrays.asList(PlatformActivitySignUpOuterStatusEnum.SIGN_UP_PASS.getCode(), PlatformActivitySignUpOuterStatusEnum.SIGN_UP_NO_PASS.getCode());

        // 商家已提交平台审核, 平台已经审核完报名
        if (signUpList.stream().filter(a -> PlatformActivitySignUpInnerStatusEnum.SUBMITTED.getCode().equals(a.getStatus())).allMatch(a -> outerExtendStatusList.contains(a.getOuterExtendStatus()))) {
            // 平台内部流程启动, 待审核报名 -> 待提交审核
            // 执行内部流转
            SimpleTaskCompleteVO simpleTaskCompleteVO = processFeignService.startSimpleProcess(loginUser.getMemberId(), loginUser.getMemberRoleId(), platformActivityDO.getInnerProcessKey(), platformActivityDO.getId());
            platformActivityDO.setInnerStatus(simpleTaskCompleteVO.getStatus());
            platformActivityDO.setInnerTaskId(simpleTaskCompleteVO.getTaskId());

            // 平台外部流程启动, 待审核报名 -> 待上线活动
            // 执行外部流转
            platformActivityDO = processFeignService.completeSimpleTaskByPlatformActivityOuter(platformActivityDO, ProcessTaskStatusEnum.GOTO_NEXT_STEP.getCode());
            platformActivityRepository.saveAndFlush(platformActivityDO);

            // 外部流转记录
            activityRecordService.savePlatformActivityOuterRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getOuterStatus(), PlatformActivityOuterStatusEnum.getMessage(platformActivityDO.getOuterStatus()), ActivityStrOperateEnum.pt_outer_audit_signup.getMessage(), "");
            // 内部流转记录
            activityRecordService.savePlatformActivityInnerRecord(loginUser, platformActivityDO.getId(), platformActivityDO.getInnerStatus(), PlatformActivityInnerStatusEnum.getMessage(platformActivityDO.getInnerStatus()), ActivityStrOperateEnum.pt_inner_audit_signup.getMessage(), "");
        }
    }
}
